from django.shortcuts import render
import datetime
from django.db.models import Q
from django.core import signing
from django.http import HttpResponse
from common.models import Customer, Room, RoomLog, waterbill
import sys

from django.core.serializers.json import DjangoJSONEncoder
from django.core.serializers import serialize
import json
# Create your views here.
calculate_time = 1
#每calculate_time分钟计费一次，主要由客户端心跳包请求时间间隔决定
mode_calculate = dict()
mode_calculate["H"] = 0.07
mode_calculate["M"] = 0.05
mode_calculate["L"] = 0.02

KEY = '2018211302'
SALT = 'BUPT'

def encrypt(obj):
    value = signing.dumps(obj, key=KEY, salt=SALT)
    value = signing.b64_encode(value.encode()).decode()
    return value


def decrypt(src):
    src = signing.b64_decode(src.encode()).decode()
    raw = signing.loads(src, key=KEY, salt=SALT)
    return raw


def checkToken(token):
     # print(token)
     temp1 = token.split("|")
     temp2 = temp1[1].split(",")
     if(decrypt(temp2[0])==temp1[0] and temp2[1]==decrypt(temp1[2])):
         return 1
     else:
         return 0


def update_money(room_id):
    bill = waterbill.objects.get(rid=room_id)
    room = Room.objects.get(rid=room_id)
    if room.onoff == 1:
        tmp = room.temp
        mode = room.mode
        cost = calculate_time*(abs(tmp-26)*0.04+mode_calculate[mode])
        bill.money += cost
        bill.time = datetime.datetime.now()
        bill.save()
    else:
        bill.time = datetime.datetime.now()
        bill.save()


def CheckIn(request):
    request.params = json.loads(request.body)
    room_id = request.params["rid"]
    pd = request.params["password"]
    dictionary = dict()
    dictionary["data"]={}

    result = Customer.objects.filter(Q(rid=room_id) & Q(state=1) & Q(password=pd))

    if result:
        dictionary["data"]["uid"] = result[0].id
        dictionary["data"]["username"] = result[0].username
        dictionary["data"]["token"] = str(room_id) +"|"+ str(encrypt(room_id)) + "," + str(result[0].checkinDate) +"|"+ \
                                      str(encrypt(str(result[0].checkinDate)))
        # token生成
        dictionary["error_code"] = 0
    else:
        dictionary["error_code"] = 1

    ret = json.dumps(dictionary)

    return HttpResponse(content=ret, content_type="application/json")


def TurnOnOff(request):
    request.params = json.loads(request.body)
    room_id = request.params["rid"]
    state = request.params["state"]
    token = request.META.get("HTTP_AUTHORIZATION")
    dictionary = dict()

    if checkToken(token):
        room = Room.objects.get(rid=room_id)
        room.onoff = state
        room.save()
        nlog = RoomLog()
        nlog.onoff=state
        nlog.rid_id = room.rid
        nlog.onoff = room.onoff
        nlog.optime = datetime.datetime.now()
        nlog.mode = room.mode
        nlog.temp = room.temp
        nlog.discount = room.discount
        nlog.save()

        dictionary["error_code"] = 0
    else:
        dictionary["error_code"] = 1

    ret = json.dumps(dictionary)

    return HttpResponse(content=ret, content_type="application/json")


def SetTmp(request):
    request.params = json.loads(request.body)
    room_id = request.params["rid"]
    tmp = request.params["settemp"]
    token = request.META.get("HTTP_AUTHORIZATION")
    dictionary = dict()
    if checkToken(token):
        room = Room.objects.get(rid=room_id)
        if room.onoff:
            if int(tmp) <= 30 and int(tmp) >= 16:
                room.temp = int(tmp)
                room.save()
                nlog = RoomLog()
                nlog.rid_id = room.rid
                nlog.optime = datetime.datetime.now()
                nlog.onoff = room.onoff
                nlog.mode = room.mode
                nlog.temp = room.temp
                nlog.discount = room.discount
                nlog.save()
                dictionary["error_code"] = 0
            else:
                dictionary["error_code"] = 1
        else:
            dictionary["error_code"] = 1
    else:
        dictionary["error_code"] = 1

    ret = json.dumps(dictionary)

    return HttpResponse(content=ret, content_type="application/json")


def SetMode(request):
    request.params = json.loads(request.body)
    room_id = request.params["rid"]
    mode = request.params["setmode"]
    token = request.META.get("HTTP_AUTHORIZATION")
    dictionary = dict()

    if checkToken(token):
        dictionary["error_code"] = 0
        room = Room.objects.get(rid=room_id)
        if room.onoff:
            room.mode = mode
            room.save()
            nlog = RoomLog()
            nlog.rid_id = room.rid
            nlog.onoff = room.onoff
            nlog.optime = datetime.datetime.now()
            nlog.mode = room.mode
            nlog.temp = room.temp
            nlog.discount = room.discount
            nlog.save()
        else:
            dictionary["error_code"] = 1
    else:
        dictionary["error_code"] = 1

    ret = json.dumps(dictionary)

    return HttpResponse(content=ret, content_type="application/json")


def ShowCost(request):
    request.params = json.loads(request.body)
    room_id = request.params["rid"]
    token = request.META.get("HTTP_AUTHORIZATION")
    dictionary = dict()
    if checkToken(token):

        update_money(room_id)
        bill = waterbill.objects.get(rid=room_id)
        room = Room.objects.get(rid=room_id)

        dictionary["data"]["onoff"] = room.onoff
        dictionary["data"]["cost"] = bill.money

        dictionary["error_code"] = 0
    else:
        dictionary["error_code"] = 1

    ret = json.dumps(dictionary)
    return HttpResponse(content=ret, content_type="application/json")